package com.dminvoicemanager;

import com.dminvoicemanager.DM_ApplicationDBLoader;
import com.dminvoicemanager.objects.Const;
import com.dminvoicemanager.services.MinuteAlarm;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.Toast;

public class DM_InvoiceLoading extends Activity {

	public static final String TAG = null;
	// private PBDatabaseAdapter dbHelper;
	ProgressDialog mProgressDialog;
	// private PBDatabaseAdapter dbHelper;
	private String DBNAME = "dminvoicemanager.db";
	private SQLiteDatabase mydb;
	private String SERVER_DETAILS = "serverinfo";
	private String ITEM_DEBTOR = "fDebtor";
	private String DB_VERSION_UPGRADE = "Fdb_version_upgrade";
	// Database Version
	private static final int OLDDB_VERSION = 5;
	private static final int DATABASE_VERSION = 6;
	JSONArray jArray, jArrayp;
	String result = null;
	String resultp = null;
	InputStream is = null;
	InputStream isp = null;
	StringBuilder sb = null;
	StringBuilder sbp = null;
	ProgressBar prgs;
	// DownloadAdministrativeDBList task;
	int arrayLength = 0;
	String connectionURL;
	// Database Helper
	DM_ApplicationDBLoader db;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_invoice_loading);
		/***************** START GPS RECORDING **********************/
		Intent intent = new Intent(getApplicationContext(), MinuteAlarm.class);

		boolean alarmUp = (PendingIntent.getBroadcast(getApplicationContext(),
				0, intent, PendingIntent.FLAG_NO_CREATE) != null);

		if (!alarmUp)// Fire Only if not fired
		{
			MinuteAlarm ma = new MinuteAlarm(getApplicationContext(),
					Const.initialDelaySeconds, Const.repeatEveryMinutes);// 1-First
																			// Alarm
																			// Delay
																			// Seconds
																			// 5-
																			// Repeat
																			// Every
																			// 5
																			// minutes

		}

		db = new DM_ApplicationDBLoader(this);
		db.getWritableDatabase();
		logDBVersion();
		Cursor cursurllist = null;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			cursurllist = mydb.query(SERVER_DETAILS, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}

		if (cursurllist == null || cursurllist.getCount() < 1) {
			Intent myIntent = new Intent(this, DM_Properties.class);
			startActivityForResult(myIntent, 0);
			finish();
			return;
		} else {
			Intent myIntent = new Intent(this, DM_InvoiceMainActivity.class);
			startActivityForResult(myIntent, 0);
			finish();
			return;
		}

	}

	// Check Database Version change Activities
	private void logDBVersion() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor curChkDbVersion = null;
		ContentValues addDbVersion = new ContentValues();
		try {
			String queryMustSale = "SELECT * from Fdb_version_upgrade";
			curChkDbVersion = mydb.rawQuery(queryMustSale, null);

		} catch (Exception e) {
		}
		if (curChkDbVersion != null) {
			if (curChkDbVersion.getCount() > 0) {
				while (curChkDbVersion.moveToNext()) {
					String versionUpgradeState = curChkDbVersion.getString(3);
					if (versionUpgradeState.equals("YES")) {
						// upGradingDebtors();
					}

				}
			} else {
				// insert version details
				try {
					addDbVersion.put("oldversion", OLDDB_VERSION);
					addDbVersion.put("newversion", DATABASE_VERSION);
					// Check upgraded version Modification Done or Pending
					addDbVersion.put("upgradeDone", "NO");
					// Check latest versions changed
					addDbVersion.put("activeupgrade", "3");
					mydb.insert(DB_VERSION_UPGRADE, null, addDbVersion);
				} catch (Exception e) {
				}
			}
		}
	}

	private void upGradingDebtors() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor curSelectDebtor = null;
		try {
			String queryMustSale = "SELECT * from fDebtor";
			curSelectDebtor = mydb.rawQuery(queryMustSale, null);

		} catch (Exception e) {
		}
		if (curSelectDebtor != null) {
			if (curSelectDebtor.getCount() > 0) {
				while (curSelectDebtor.moveToNext()) {
					String debReadId = curSelectDebtor.getString(0);
					String debCodeRead = curSelectDebtor.getString(1);
					String debNameRead = curSelectDebtor.getString(2);
					String DebSumLog = debCodeRead + " : " + debNameRead;
					Log.v(TAG, "DebSumLog:" + DebSumLog);
					ContentValues updateDebSumary = new ContentValues();
					updateDebSumary.put("DebSumary", DebSumLog);// Add

					mydb.update(ITEM_DEBTOR, updateDebSumary, "_id ='"
							+ debReadId + "'", null);
				}
			}
		}
		updateDBUpgrade();
	}

	private void updateDBUpgrade() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		// String[] resultserial = { "tempRepInvSerial" };
		Cursor curUpdateDbVersion = null;
		ContentValues updateDbVersion = new ContentValues();
		try {
			String queryMustSale = "SELECT * from Fdb_version_upgrade";
			curUpdateDbVersion = mydb.rawQuery(queryMustSale, null);

		} catch (Exception e) {
		}
		if (curUpdateDbVersion != null) {
			if (curUpdateDbVersion.getCount() > 0) {
				while (curUpdateDbVersion.moveToNext()) {
					String fdb_Ver_id = curUpdateDbVersion.getString(4);
					updateDbVersion.put("upgradeDone", "YES");
					mydb.update(DB_VERSION_UPGRADE, updateDbVersion,
							"activeupgrade ='1'", null);
				}
			}
		}
	}
}
